package com.choosefine.it.common.aop;

import com.choosefine.it.common.def.ResultCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.exception.RespExcption;
import com.choosefine.it.common.json.JsonResult;
import com.choosefine.it.common.json.JsonUtil;

/**
 * 过滤web请求,并处理自定义断言异常
 * 
 * @desc
 * @author 戚羿辰
 * @Date 2017/01/12
 */
@Component
@Aspect
public class WebControllerAspect
{

	private static final Logger logger = LoggerFactory.getLogger("api service v1");

	// 拦截web请求
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Around("execution(* com.choosefine.it.*.controller.*Controller.*(..))")
	public Object doControllerAround(ProceedingJoinPoint pjp) throws Throwable {
		JsonResult<Integer> jsonResult = null;
		Object result = null;
		try
		{
			result = pjp.proceed();
		} catch (RespExcption e)
		{
			// 断言时抛出的错误
			jsonResult = new JsonResult(e.getMessage(), e.getCode());
			result = JsonUtil.toJson(jsonResult);
		} catch (BusinessException e)
		{
			jsonResult = new JsonResult(e.getMessage(), e.getStatusCode(), ResultCode.FAILED);
			result = JsonUtil.toJson(jsonResult);
		} catch (Exception e)
		{
			// 程序内部错误, 交给 Whitelabel Error Page 处理
			logger.error(e.getMessage());
			throw e;
		}
		return result;
	}

}
